<template>
	<view class="container bg-drak" :class="{ 'margin-bottom-big': !empty }">
		<!-- 00. 未授权登录 -->
		<use-empty v-if="!islogin" e-style="round" e-type="unauthorized" tip="当前未授权" btn-tip="去登录" height="70vh"
			:auto="false" @goto="tologin"></use-empty>
		<!-- 00. 空白页 -->

		<use-empty v-if="empty && islogin" e-style="round" e-type="cart" tip="购物车数据为空" height="70vh"></use-empty>
		<!-- 00. 列表 -->
		<view v-if="!empty && islogin">
			<!-- 01. 购物车列表 -->
			<view class="cart-list padding-sm">
				<block v-for="(item, index) in cartDatas" :key="item.id">
					<view class="cart-item bg-main margin-bottom-sm padding-lg pos-r dflex-s border-radius">
						<view class="image-wrapper pos-r" @click="togoods(item)">
							<!-- 商品图片 -->
							<image class="border-radius-xs wh-full" mode="aspectFill" :lazy-load="true"
								:src="item.defaultImg">
							</image>
							<!-- 选中|未选中按钮 -->
							<view v-if="item.inventory > 0 && item.inventory >= item.shoppingcarts_products.pcount"
								class="iconfont checkbox pos-a bg-main border-radius-big"
								:class="{active: item.checked, iconxuanzhongzhuangtai: item.checked, iconweixuanzhongzhuangtai: !item.checked}"
								@tap.stop="check('item', index)"></view>

							<view v-if="(item.inventory < 10 || item.inventory < item.shoppingcarts_products.pcount)"
								class="disabled dflex-c dflex-flow-c pos-a pos-tl-c border-radius-c">
								<text>库存不足</text><text class="margin-left-xs fs-xs"
									v-if="item.stock_num > 0">剩余{{item.inventory}}</text>
							</view>
						</view>
						<view class="item-right padding-left pos-r">
							<!-- 商品名称 -->
							<view class="clamp-2 title" @click="togoods(item)">
								{{item.title}}
							</view>
							<!-- <view class="ft-dark fs-xs padding-top-xs">{{ item.goods_sku.spec || '&nbsp;&nbsp;' }}</view> -->
							<view class="padding-tb-sm">
								<text
									class="price">{{ item.discountPrice > 0 ? item.discountPrice : item.price }}</text>
								<text class="m-price" v-if="item.discountPrice > 0">{{ item.price }}</text>
							</view>

							<!-- + - 购物车数量 -->
							<use-number-box :min="1" :max="item.inventory || 1"
								:value="item.shoppingcarts_products.pcount"
								:is-max="item.shoppingcarts_products.pcount>= item.inventory"
								:is-min="item.shoppingcarts_products.pcount === 1" :index="index"
								:disabled="item.shoppingcarts_products.pcount >= item.inventory"
								@eventChange="numberChange">
							</use-number-box>
						</view>

						<!-- 删除 -->
						<view class="del-btn iconfont iconlajitong-01 pos-a border-radius-c dflex-c ft-dark fs-xl"
							@tap.stop="deleteCart(item.shoppingcarts_products.id)"></view>
					</view>
				</block>
			</view>

			<!-- 02. 底部操作栏 -->
			<view class="action-section dflex w-full bg-main pos-f padding-right">
				<view class="checkbox pos-r h-full dflex-c">
					<view class="padding-lr iconfont"
						:class="{active:allChecked,iconxuanzhongzhuangtai: allChecked, iconweixuanzhongzhuangtai: !allChecked}"
						@click="check('all')"></view>
					<view class="clear-btn pos-a tac ft-white" :class="{ show: allChecked }" @click="clearCart">清空
					</view>
				</view>
				<view class="total-box flex1 tar padding-right-lg">
					<text class="price">{{total || 0}}</text>
				</view>
				<button type="primary" class="payment no-border border-radius-lg fs" @click="createOrder">去结算</button>
			</view>
		</view>

	</view>
</template>

<script>
	const _cart = 'usemall-goods-cart'
	import {
		mapState
	} from 'vuex';

	import {
		queryCartApi,
		updateCartApi,
		deleteOneGoodsApi,
		deleteManyShoppingsApi,
	} from "@/api/user.js";

	export default {
		computed: {
			...mapState(['islogin', 'member'])
		},
		data() {
			return {

				//购物车ID
				usercartId: null,
				// 空白页
				empty: false,
				// 购物车数据
				cartDatas: [],
				// 全选状态
				allChecked: false,
				// 总价格
				total: 0,
			};
		},
		watch: {
			//显示空白页
			cartDatas(e) {
				let empty = e.length === 0;
				if (this.empty !== empty) {
					this.empty = empty;
				}
			}
		},
		// 监听页面显示。页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面
		onShow() {

			this.loadData();
			// console.debug(this.member, "<===== memberonShow")
		},


		methods: {
			//请求数据
			async loadData() {
				Promise.all([
					this.getCartFunc(),

					// this.queryActivitysFunc(),
				]).then(() => {
					this.calcTotal();
				}).catch((err) => {
					console.log(err, "<====")
				});

			},



			async getCartFunc(e) {
				const response = await queryCartApi({
					uid: this?.member?.id ?? ""
				}).catch(() => {});
				// console.log('🚀🚀🚀🚀🚀 response - queryCartApi: ', response);
				if (response?.code === 200) {
					this.usercartId = (response?.data?.records?.length > 0 ? response.data.records : [{
						id: ""
					}])[0].id;
					let _data = (response?.data?.records ?? [{
						products: []
					}])[0]?.products ?? [];

					// this.cartDatas = response?.data ?? [];
					_data.forEach(item => {
						item.discountPrice = 0;
						if (parseFloat(item?.shoppingcarts_products?.sprice ?? 0) > 0) {
							item.discountPrice = parseFloat(item?.shoppingcarts_products?.sprice ?? 0);
						}
					})
					this.cartDatas = _data;
					// console.log(this.cartDatas, "<==============this.cartDatas")
				} else {
					this.cartDatas = [];
				}
			},




			// 跳转登录页
			tologin() {
				this.$api.tologin();
			},
			// 跳转商品页
			togoods(item) {
				// console.log(item,"<==========togoods.item")
				// debug();
				this.$api.togoods({
					id: item.id
				});
			},

			// 选中状态处理
			check(type, index) {
				if (type === 'item') {
					const _item = this.cartDatas[index];
					Object.assign(_item, {
						checked: !_item?.checked
					})
					this.cartDatas.splice(index, 1, _item);
					// console.debug(this.cartDatas, "<=== this.cartDatas")
				} else {
					const checked = !this.allChecked
					this.cartDatas.forEach(item => {
						item.checked = checked;
					})
					this.allChecked = checked;
				}
				this.calcTotal();
			},

			// +- 数量
			async numberChange(data) {
				let cart = this.cartDatas[data.index];
				if (cart?.shoppingcarts_products?.pcount <= 0) {
					this.$api.msg("数量不能小于0");
					return;
				}
				const response = await updateCartApi({
					// uid: this?.member?.id ?? ""
					// ...this.Shoppingcart_search,
					sid: this?.usercartId ?? "",
					pid: cart.id ?? "",
					// pcount: this?.cartDatas?.shoppingcarts_products?.pcount ?? "",
					pcount: data.number,

				}).catch(() => {});
				if (response?.code === 200) {
					cart.shoppingcarts_products.pcount = data.number;

					this.calcTotal();
				}
				// this.loadData();
			},
			// 删除
			deleteCart(id) {
				const that = this;
				uni.showModal({
					title: '提示',
					content: '删除购物车',
					success: async function(res) {
						if (res.confirm) {
							const response = await deleteOneGoodsApi({
								id: id
							}).catch(() => {});
							if (response?.code === 200) {
								that.loadData();
							} else {
								that.$api.msg(response?.msg ?? "服务器繁忙，请稍后再试");
							}
						}
					}
				});
			},
			// 清空
			clearCart() {
				let _this = this;
				uni.showModal({
					title: '提示',
					content: '清空购物车',
					success: function(res) {
						if (res.confirm) {
							_this.deleteManyShoppingsFunc();
						}
					}
				});
			},
			// 计算总价
			calcTotal() {
				if (this.cartDatas.length === 0) {
					this.empty = true;
					return;
				}

				let total = 0,
					checked = true;

				this.cartDatas.forEach(item => {
					if (item.checked) {
						// 存在库存
						if (item.inventory > 0 && item.inventory >= item.shoppingcarts_products.pcount) {
							total += (item?.discountPrice > 0 ? item.discountPrice : item.price) * item
								.shoppingcarts_products.pcount;
						}
					} else if (checked) {
						checked = false;
					}
				})

				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			// 创建订单
			createOrder() {
				let cart_ids = [];
				// console.log(this.cartDatas, "<====");
				this.cartDatas.forEach(item => {
					// 选中有库存购物车
					if (item.checked && item.inventory > 0 && item.inventory > item.shoppingcarts_products
						.pcount) {
						cart_ids.push(item.id)
					}
				})
				if (cart_ids.length <= 0) {
					this.$api.msg('请选择结算商品')
					return;
				}
				uni.navigateTo({
					url: `/pages/order/create?cart_ids=${cart_ids.join(',')}`
				})
			},
			// ************************************************ 接口函数
			async deleteManyShoppingsFunc() {
				uni.showLoading({
					title: "加载中...",
					icon: "none",
				})
				const response = await deleteManyShoppingsApi({
					uid: this?.member?.id ?? ""
				}).catch(() => {});
				if (response?.code === 200) {
					this.$api.msg("购物车清空成功");
					this.loadData();
				} else {
					this.$api.msg(t = response?.msg ?? "服务器繁忙，请稍后再试");
				}
				uni.hideLoading();
			},
		},
	}
</script>

<style lang='scss' scoped>
	page {
		min-height: 100%;
	}

	/* 购物车列表项 */
	.cart-item {

		&:last-child {
			margin-bottom: 100rpx;
		}

		.image-wrapper {
			width: 230rpx;
			height: 230rpx;
			flex-shrink: 0;

			image {
				opacity: 1;
			}
		}

		.checkbox {
			top: -16rpx;
			left: -16rpx;
			color: $font-color-disabled;
			line-height: 1;
			font-size: 46rpx;
			padding: 5rpx;
			z-index: 8;
		}

		.disabled {
			color: #fff !important;
			width: 70%;
			height: 70%;
			background-color: rgba(51, 51, 51, 0.5);
		}

		.item-right {
			height: 260rpx;
			overflow: hidden;
		}

		.del-btn {
			bottom: 40rpx;
			right: 30rpx;
			width: 70rpx;
			height: 70rpx;
		}
	}

	/* 底部栏 */
	.action-section {
		z-index: 999;
		bottom: 0;
		height: 100rpx;

		.checkbox {
			.iconfont {
				font-size: 46rpx;
				color: #2C405A;
			}
		}

		.clear-btn {
			left: 100rpx;
			background: #2C405A;
			border-radius: 0 50rpx 50rpx 0;
			padding: 12rpx 0;
			transition: all .2s;

			width: 0;
			opacity: 0;

			&.show {
				width: 120rpx;
				opacity: 1;
			}
		}

		.payment {
			padding: 0 40rpx;
			font-size: $font-base;
			background: $uni-color-primary;
			box-shadow: 1px 2px 5px rgba(217, 60, 93, 0.72)
		}
	}

	/* #ifdef H5 || MP-360 */
	.action-section {
		margin-bottom: 50px;
	}

	/* #endif */
</style>